package com.zlzlib.libuimodel.ui;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;

import com.zlzlib.librx.TUtil;
import com.zlzlib.libui.fragment.BaseFragment;
import com.zlzlib.libuimodel.bean.SourceData;
import com.zlzlib.libuimodel.model.BaseViewModel;
import com.zlzlib.libuimodel.model.RxDataModel;


/**
 * Created by zlz on 2019/9/2.
 */
public abstract class BaseModelFragment<T extends BaseViewModel<? extends RxDataModel>, B extends ViewDataBinding> extends BaseFragment<B> {

    protected T mViewModel;

    protected abstract void pageData(SourceData source);

    protected abstract void pageLoading(SourceData source);

    protected abstract void pageTip(SourceData source);

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mViewModel = initViewMode(isModelFromActivity(), TUtil.getInstance(this, 0));
    }

    /**
     * 初始化ViewMode
     *
     * @param isModelFromActivity 是否公用activity的 viewModel
     * @param tClass              继承 BaseViewModel 的类
     */
    protected <M extends BaseViewModel<? extends RxDataModel>> M initViewMode(boolean isModelFromActivity, Class<M> tClass) {
        M baseViewModel;
        if (isModelFromActivity) {
            baseViewModel = Utils.getBaseViewModel(getActivity(), tClass);
        } else {
            baseViewModel = Utils.getBaseViewModel(this, tClass);
        }
        baseViewModel.addPageDataObserve(this, getClass().getSimpleName(), observerData);
        baseViewModel.addPageLoadingObserve(this, getClass().getSimpleName(), observerLoading);
        baseViewModel.addPageTipObserve(this, getClass().getSimpleName(), observerTip);
        return baseViewModel;
    }

    protected final Observer<SourceData> observerData = this::pageData;

    protected final Observer<SourceData> observerLoading = this::pageLoading;

    protected final Observer<SourceData> observerTip = this::pageTip;

    /**
     * @return view model是否和父类activity共有  数据共享使用
     */
    protected boolean isModelFromActivity() {
        return false;
    }
}
